package com.woniu.teachmall.controller;

import com.woniu.teachmall.dto.CarItem;
import com.woniu.teachmall.dto.OrderGroup;
import com.woniu.teachmall.dto.OrderItem;
import com.woniu.teachmall.entity.Address;
import com.woniu.teachmall.entity.User;
import com.woniu.teachmall.service.AddressService;
import com.woniu.teachmall.service.ShopcarService;
import com.woniu.teachmall.service.service.OrderService;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 订单管理控制器
 * 处理订单创建、支付、展示等全流程业务
 */
@Controller
public class OrderController {
    @Autowired
    private AddressService addressService;
    @Autowired
    private OrderService orderService;
    @Autowired
    private ShopcarService shopcarService;

    /**
     * 获取用户订单列表
     * @param session 用户会话对象
     * @param model 视图模型
     * @return 订单列表页面视图或登录页面
     */
    @GetMapping("/orders")
    public String orders(HttpSession session, Model model) {
        // 验证用户登录状态
        User user = (User) session.getAttribute("loginUser");
        if (user == null) {
            return "login";
        }

        // 获取并处理订单数据
        Integer userId = user.getId();
        List<OrderItem> orderlist = orderService.getOrder(userId);

        // 按订单号分组处理
        Map<String, List<OrderItem>> orderMap = orderlist.stream()
                .collect(Collectors.groupingBy(OrderItem::getNumber));

        // 转换为订单组结构
        List<OrderGroup> orderGroups = orderMap.entrySet().stream()
                .map(entry -> new OrderGroup(entry.getKey(), entry.getValue()))
                .collect(Collectors.toList());

        model.addAttribute("orderGroups", orderGroups);
        return "orders";
    }

    /**
     * 进入订单创建页面
     * @param session 用户会话对象
     * @param model 视图模型
     * @return 订单创建页面视图或登录页面
     */
    @GetMapping("/order/add")
    public String orderadd(HttpSession session, Model model) {
        User user = (User) session.getAttribute("loginUser");
        if (user == null) {
            return "redirect:/user/login";
        }

        // 获取订单创建所需数据
        Integer userId = user.getId();
        List<Address> addressList = addressService.getAddress(userId);
        List<CarItem> car = shopcarService.getCar(userId);
        Double totalPrice = shopcarService.getTotalPrice(userId);

        // 设置视图模型数据
        model.addAttribute("addresses", addressList);
        model.addAttribute("carItems", car);
        model.addAttribute("totalPrice", totalPrice);
        return "order_add";
    }

    /**
     * 提交订单
     * @param addressId 收货地址ID
     * @param payType 支付方式
     * @param session 用户会话对象
     * @param model 视图模型
     * @return 订单提交确认页面视图
     */
    @PostMapping("/order/submit")
    public String ordersubmit(Integer addressId, String payType, HttpSession session, Model model) {
        User user = (User) session.getAttribute("loginUser");
        if (user == null) {
            return "redirect:/user/login";
        }

        // 生成订单并获取订单信息
        Integer userId = user.getId();
        String orderNo = orderService.submitOrder(userId, addressId, user.getTelphone(), payType, session);
        Double totalPrice = shopcarService.getTotalPrice(userId);

        // 设置支付信息
        model.addAttribute("OrderNo", orderNo);
        model.addAttribute("totalPrice", totalPrice);
        model.addAttribute("payType", payType);
        return "order_submit";
    }

    /**
     * 立即支付接口
     * @param orderId 订单ID
     * @param session 用户会话对象
     * @return 支付结果状态码（JSON格式）
     */
    @PostMapping("/order/pay/now")
    @ResponseBody
    public String payOrder(String orderId, HttpSession session) {
        User user = (User) session.getAttribute("loginUser");
        if (user == null || "".equals(orderId)) {
            return "login";
        }
        return orderService.payOrder(user.getId(), orderId, session);
    }

    /**
     * 支付宝支付回调处理
     * @param session 用户会话对象
     * @return 支付结果页面视图
     */
    @GetMapping("/alipay/return")
    public String returnOrder(HttpSession session) {
        User user = (User) session.getAttribute("loginUser");
        String orderId = session.getAttribute("orderId").toString();

        // 验证支付回调参数
        if (user == null) {
            return "login";
        }
        if (orderId == null || "".equals(orderId)) {
            return "redirect:/car";
        }

        // 处理支付成功逻辑
        orderService.orderSuccess(orderId, user.getId());
        return "pay_suc";
    }
}